package com.vision.service.impl;

import com.vision.mapper.TagMapper;
import com.vision.mapper.VideoMapper;
import com.vision.mapper.VideoTagMapper;
import com.vision.pojo.entity.Tag;
import com.vision.pojo.vo.UpdateTagListVO;
import com.vision.service.TagService;
import com.vision.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private VideoTagMapper videoTagMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private TagMapper tagMapper;

    /**
     * 给视频添加标签
     * @param tagList 标签列表
     */
    @Override
    public void addTagToVideo(Integer[] tagList) {
        // 1. 获取当前用户 ID
        Integer userId = getUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        // 2. 查询当前用户视频中 state 为 2 的视频 ID
        Integer videoId = videoMapper.selectVideoIdByState(userId);
        if (videoId == null) {
            throw new RuntimeException("当前用户没有上传视频");
        }
        // 3. 给视频添加标签
        videoTagMapper.addTagToVideo(videoId, tagList);
    }

    /**
     * 获取所有标签
     * @return 所有标签
     */
    @Override
    public List<Tag> getAllTag() {
        return  tagMapper.selectAllTag();
    }

    /**
     * 根据视频 id 获取标签
     * @param videoId 视频 id
     * @return 标签列表
     */
    @Override
    public List<Tag> getTagByVideoId(Integer videoId) {
        return tagMapper.selectTagByVideoId(videoId);
    }

    /**
     * 根据视频 ID 更改标签
     * @param updateTagListVO 标签列表对象
     */
    @Override
    public void updateTagToVideo(UpdateTagListVO updateTagListVO) {
        // 1. 删除原有的所有标签
        videoTagMapper.deleteTagByVideoId(updateTagListVO.getVideoId());
        // 2. 添加新的标签
        videoTagMapper.addTagToVideo(updateTagListVO.getVideoId(), updateTagListVO.getTagList());
    }

    /**
     * 获取当前登录用户 ID
     * @return 用户 ID
     */
    private Integer getUserId() {
        Map<String, Integer> userInfo = ThreadLocalUtil.get();
        return userInfo.get("id");
    }
}
